#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <unordered_map>
#include "Common.hpp"
#include "Log.hpp"

const std::string Sep = "\r\n";
const std::string LineSep = " "; // 行分隔符
const std::string HeaderLineSep = ": "; // 属性分隔符
const std::string BlankLine = Sep;
const std::string defaulthomepage = "wwwroot"; // 自定义的 web 根目录
const std::string http_version = "HTTP/1.0";
const std::string page404 = "wwwroot/404.html";
const std::string firstpage = "index.html";

using namespace LogModule;

// B/S 模式 -- 由浏览器当客户端了

class HttpRequest
{
public:
    HttpRequest() {}
    ~HttpRequest() {}

    bool IsHasArgs()
    {
        return _isexec;
    }

    // GET /favicon.ico HTTP/1.1
    // Host: 1.12.51.69:8080
    // Connection: keep-alive
    // User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 SLBrowser/9.0.5.12181 SLBChan/105 SLBVPV/64-bit
    // Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
    // Referer: http://1.12.51.69:8080/
    // Accept-Encoding: gzip, deflate
    // Accept-Language: zh-CN,zh;q=0.9

    bool ParseHeaderkv()
    {
        std::string key, value;
        for (auto& header : _req_header)
        {
            // Connection: keep-alive -> 以 ": " 分割字符串为 Kv
            if (SplitString(header, HeaderLineSep, &key, &value))
            {
                _headerkv.insert(std::make_pair(key, value));
            }
        }
        return true;
    }

    bool ParseHeader(std::string& request_str)
    {
        std::string line;
        while (true)
        {
            bool r = ParseOneLine(request_str, &line, Sep);
            if (r && !line.empty())
            {
                _req_header.push_back(line);
            }
            else if (r && line.empty()) // 读到了 空行
            {
                _blank_line = Sep;
                break;
            }
            else return false; // 解析失败
        }
        ParseHeaderkv();
        return true;
    }

    void Deserialize(std::string& request_str)
    {
        // std::cout << "########################" << std::endl;
        // std::cout << "之前： request:\n" << request_str;

        // if(ParseOneLine(request_str, &_req_line, Sep)) // _req_line 在这里被初始值
        // {
        //     // 提取请求行中的详细字段
        //     ParReqLine(_req_line, LineSep);
        // }
        // std::cout << "之后： request:\n" << request_str;
        // Print();
        // std::cout << "########################" << std::endl;

        if (ParseOneLine(request_str, &_req_line, Sep)) // 1. 解析请求报头
        {
            // 提取请求行详细字段
            ParReqLine(_req_line, LineSep);
            ParseHeader(request_str);   // 2. 报头继续请求
            _body = request_str;        // 3. 获取正文
            // // 分析请求中： 是否含有参数 ..
            if(_method == "POST")
            {
                _isexec = true; // 参数在正文
                _args = _body;
                _path = _uri;
                LOG(LogLevel::DEBUG) << "POST: _path" << _path;
                LOG(LogLevel::DEBUG) << "POST: _args" << _args;
            }
            else if(_method == "GET")
            {
                auto pos = _uri.find("?");
                if(pos != std::string::npos)
                {
                    _isexec = true;
                    // /login?name=aa&password=123
                    _path = _uri.substr(0, pos); // ? 前的
                    _args = _uri.substr(pos + 1); // ? 后的
                    LOG(LogLevel::DEBUG) << "GET: _path" << _path;
                    LOG(LogLevel::DEBUG) << "GET: _args" << _args;
                }
            }
        }
    }

    std::string GetContent(const std::string path)
    {
        std::string content;
        std::ifstream in(path, std::ios::binary);
        if(!in.is_open()) return std::string();
        in.seekg(0, in.end);
        int filesize = in.tellg();
        in.seekg(0, in.beg);

        content.resize(filesize);
        in.read((char*)content.c_str(), filesize);

        in.close();
        LOG(LogLevel::DEBUG) << "content length: " << content.size();


        // std::string content;
        // std::ifstream in(_uri);
        // if (!in.is_open()) return std::string();
        // std::string line;
        // while (std::getline(in, line))
        // {
        //     content += line;
        // }
        // in.close();

        return content;
    }

    void Print()
    {
        std::cout << "_method: " << _method << std::endl;
        std::cout << "_uri: " << _uri << std::endl;
        std::cout << "_version: " << _version << std::endl;

        for (auto& kv : _headerkv) {
            std::cout << kv.first << " # " << kv.second << std::endl;
        }

        std::cout << "_blank_line: " << _blank_line << std::endl;
        std::cout << "_body: " << _body << std::endl;
    }

    std::string Uri()
    {
        return _uri;
    }

    void SetUri(const std::string newuri)
    {
        _uri = newuri;
    }

    std::string Path() {return _path;}
    std::string Args() {return _args;}

    std::string Suffix()
    {
        // _uri -> wwwroot/index.html wwwroot/image/1.jpg wwwroot/login.html
        auto pos = _uri.rfind(".");
        if (pos == std::string::npos) return std::string(".html");
        else return _uri.substr(pos);
    }


private:
    // 从 HTTP 请求行中提取方法（_method）、URI（_uri）和版本（_version），并将 _uri 与一个默认主页路径（defaulthomepage）拼接
    void ParReqLine(std::string& _req_line, const std::string Sep)
    {
        (void)Sep;
        std::stringstream ss(_req_line); // 流式分隔
        ss >> _method >> _uri >> _version;
        // _uri = defaulthomepage + _uri; // 不用了
    }

    std::string _req_line;                  // 首行
    std::vector <std::string> _req_header;  // 请求报头
    std::string _blank_line;                // 空行
    std::string _body;                      // 请求正文

    // 在反序列化的过程中，细化我们解析出来的字段
    std::string _method;
    std::string _uri;
    std::string _version;
    std::unordered_map<std::string, std::string> _headerkv;

    bool _isexec = false;
    std::string _path;
    std::string _args;

    // std::vector<std::string> _cookies; // 其实cookie可以有多个，因为Set-Cookie可以被写多条，测试，一条够了。
    // std::string _sessionid;            // 请求携带的sessionid，仅仅用来测试

};



// 对于 http 任何请求都要有应答
class HttpResponse
{
public:
    HttpResponse() : _verion(http_version), _blank_line(Sep)
    {}
    ~HttpResponse()
    {}

    void Build(HttpRequest& req)
    {
        // std::string uri = req.Uri(); // wwwroot/   wwwroot/a/b/
        // if (uri.back() == '/')
        // {
        //     _status_code = 301;
        //     _status_desc = Code2Desc(_status_code); // 和状态码是强相关的！
        //     SetHeader("Location", "http://8.137.19.140:8888/register.html");
        //     for (auto &header : _header_kv)
        //     {
        //         _resp_header.push_back(header.first + HeaderLineSep + header.second);
        //     }
        //     LOG(LogLevel::DEBUG) << "------客户端在请求: " << req.Uri();
        //     return;
        // }

        //std::string uri = req.Uri(); // wwwroot/ wwwroot/a/b/
        std::string uri = defaulthomepage + req.Uri(); 
        
        if (uri.back() == '/')
        {
            uri += firstpage; // wwwroot/index.html
            // req.SetUri(uri); 
        }
        LOG(LogLevel::DEBUG) << "----- 客户端在请求：" << req.Uri();
        req.Print();
        LOG(LogLevel::DEBUG) << "--------------------------";

        _content = req.GetContent(uri);
        // LOG(LogLevel::DEBUG) << "content length: " << _content.size();

        if (_content.empty())
        {
            // 用户请求的资源并不存在
            _status_code = 404;
            // req.SetUri(page404); 
            _content = req.GetContent(page404);
        }
        else
        {
            _status_code = 200;
        }
        // LOG(LogLevel::DEBUG) << "客户端在请求：" << req.Uri();
        // req.Print();
        // LOG(LogLevel::DEBUG) << "--------------------------";

        _status_desc = Code2Desc(_status_code); // 和状态码强相关

        if(!_content.empty())
        {
            SetHeader("Content-Length", std::to_string(_content.size()));
        }
        
        std::string mime_type = Suffix2Desc(req.Suffix());
        SetHeader("Content-Type", mime_type);
        
        _body = _content; // 正文

        // for(auto &header: _header_kv)
        // {
        //     _resp_header.push_back(header.first + HeaderLineSep + header.second);
        // }
    }

    void SetCode(int code)
    {
        _status_code = code;
        _status_desc = Code2Desc(_status_code);
    }

    void SetBody(const std::string &body)
    {
        _body = body;
    }

    void SetHeader(const std::string& k, const std::string& v)
    {
        _header_kv[k] = v;
    }

    void Serialize(std::string* resp_str)
    {
        for(auto &header: _header_kv)
        {
            _resp_header.push_back(header.first + HeaderLineSep + header.second);
        }
        
        // 首行: 版本+ 空格 + 状态码 + 空格 + 状态码描述 + 换行符 
        _resp_line = _verion + LineSep + std::to_string(_status_code) + LineSep + _status_desc + Sep;
        // _body = _content; // 正文

        // 序列化
        *resp_str = _resp_line;
        for (auto& line : _resp_header)
        {
            *resp_str += (line + Sep);
        }
        *resp_str += _blank_line;
        *resp_str += _body;
    }

private:
    std::string Code2Desc(int code)
    {
        switch (code)
        {
        case 200: return "OK";
        case 404: return "Not Found";
        case 301: return "Moved Permanently";
        case 302: return "Found";
        default: return std::string();
        }
    }

    std::string Suffix2Desc(const std::string& suffix)
    {
        if (suffix == ".html") return "text/html";
        else if (suffix == ".jpg") return "application/x-jpg";
        else return "text/html";
    }

private:

    // 必备要素
    std::string _verion;
    int _status_code; // 状态码
    std::string _status_desc; // 状态码描述
    std::unordered_map<std::string, std::string> _header_kv;

    std::string _resp_line;
    std::vector<std::string> _resp_header;
    std::string _blank_line;
    std::string _body;
    std::string _content;
};

